package controllers

import (
	"godemo/app/form"
	"godemo/common"
	"godemo/common/ar"
	"godemo/common/helper"
	"log"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

//用户登陆
func UserLogin(c *gin.Context) {
	var loginForm form.Login

	loginForm.Username = c.PostForm("username")
	loginForm.Password = c.PostForm("password")
	loginForm.Code = c.PostForm("code")
	loginForm.CodeId = c.PostForm("code_id")

	err := form.ValidateLoginForm(loginForm)

	var viewData = gin.H{"title": "用户登陆"}

	log.Println(c.Request.PostForm)

	if len(err) > 0 {
		var child = make(map[string]string)
		for k, v := range err {
			child[k] = strings.Join(v, ",")
		}
		viewData["err"] = child

	} else {
		if u, err := ar.GetByUsername(loginForm.Username); err != nil {
			viewData["err"] = map[string]string{"username": "用户名不存在"}
		} else {
			if u.Password != helper.Sha1String(loginForm.Password) {
				viewData["err"] = map[string]string{"password": "密码错误"}
			} else {
				common.SessionPut("uid", helper.UintToString(u.ID))
				c.Redirect(http.StatusMovedPermanently, "/user/index")
				return
			}
		}
	}

	//log.Println(viewData)
	viewData["username"] = loginForm.Username
	viewData["password"] = loginForm.Password
	viewData["code"] = loginForm.Code

	c.HTML(http.StatusOK, "login.html", viewData)

}

//用户退出
func UserLogOut(c *gin.Context) {
	common.SessionFlush()
	c.Redirect(http.StatusMovedPermanently, "/login")
}

func UserIndex(c *gin.Context) {
	rows, pageData := ar.UserRows(c)
	c.HTML(http.StatusOK, "user.html", gin.H{"title": "用户中心", "rows": rows, "p": pageData})
}

func UserDel(c *gin.Context) {
	id, err := strconv.Atoi(c.Query("id"))
	if err != nil {
		c.String(http.StatusOK, "error:")
	} else {
		ar.UserDel(uint(id))
		c.Redirect(http.StatusMovedPermanently, c.Request.Referer())
	}

}
